package com.ita.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ita.dao.CustomerDao;
import com.ita.pojo.Customer;
import com.ita.util.DBUtil;
@Repository(value="cusDao")
public class CustomerDaoImpl implements CustomerDao {

	@Override
	public int addCustomer(Customer c) {
		Connection connection = null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			String sql = "insert into customer values(?,?,?,?,?)";
			connection = DBUtil.createByDs();
			pst = connection.prepareStatement(sql);
			pst.setString(1, c.getId());
			pst.setString(2, c.getName());
			pst.setBoolean(3, c.isSex());
			pst.setDouble(4, c.getSal());
			pst.setDate(5, new java.sql.Date(c.getBirth().getTime()));
			m = pst.executeUpdate();
			return m;
		} catch (Exception e) {
			return m;
		} finally {
			DBUtil.close(connection, pst, null);
		}
	}

	@Override
	public List<Customer> findAllCustomers() {
		String sql = "select * from customer";
		Connection connection = null;
		PreparedStatement pst = null;
		Customer c = null;
		List<Customer> list = new ArrayList<Customer>();
		ResultSet rs = null;
		try {
			connection = DBUtil.createByDs();
			pst = connection.prepareStatement(sql);
			rs = pst.executeQuery();
			while (rs.next()) {
				c = new Customer();
				c.setId(rs.getString("id"));
				c.setName(rs.getString("name"));
				c.setSex(rs.getBoolean("sex"));
				c.setSal(rs.getDouble("sal"));
				c.setBirth(rs.getDate("birth"));
				list.add(c);
			}
			return list;
		} catch (SQLException e) {
			return list;
		} finally {
			DBUtil.close(connection, pst, rs);
		}
	}

	@Override
	public int updateCustomer(Customer c) {
		String sql = "update customer set name=?, sex=?, sal=?, birth=? where id=?";
		Connection connection = null;
		PreparedStatement pst = null;
		try {
			connection = DBUtil.createByDs();
			pst = connection.prepareStatement(sql);
			pst.setString(1, c.getName());
			pst.setBoolean(2, c.isSex());
			pst.setDouble(3, c.getSal());
			pst.setDate(4, new java.sql.Date(c.getBirth().getTime()));
			pst.setString(5, c.getId());
			pst.executeUpdate();
			return 1;
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			return 0;
		} finally {
			DBUtil.close(connection, pst, null);

		}
	}

	@Override
	public int deleteCustomer(String id) {
		String sql = "delete from customer where id=?";
		Connection connection = null;
		PreparedStatement pst = null;
		try {
			connection = DBUtil.createByDs();
			pst = connection.prepareStatement(sql);
			pst.setString(1, id);
			pst.executeUpdate();
			return 1;
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			return 0;
		} finally {
			DBUtil.close(connection, pst, null);

		}
	}

}
